package com.ruoyi.drone.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.drone.domain.DroneUserProfile;
import com.ruoyi.drone.domain.DroneOrganization;
import com.ruoyi.drone.domain.DronePilotCertificate;
import com.ruoyi.drone.domain.DronePilotSkill;
import com.ruoyi.drone.domain.dto.DroneRegisterDTO;
import com.ruoyi.drone.domain.dto.DroneOrganizationRegisterDTO;
import com.ruoyi.drone.mapper.DroneUserProfileMapper;
import com.ruoyi.drone.mapper.DroneOrganizationMapper;
import com.ruoyi.drone.mapper.DronePilotCertificateMapper;
import com.ruoyi.drone.mapper.DronePilotSkillMapper;
import com.ruoyi.drone.service.IDroneRegisterService;

/**
 * 无人机系统注册服务实现
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class DroneRegisterServiceImpl implements IDroneRegisterService 
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private DroneUserProfileMapper userProfileMapper;

    @Autowired
    private DroneOrganizationMapper organizationMapper;

    @Autowired
    private DronePilotCertificateMapper certificateMapper;

    @Autowired
    private DronePilotSkillMapper skillMapper;

    /**
     * 飞手注册
     */
    @Override
    @Transactional
    public boolean registerPilot(DroneRegisterDTO registerDTO) 
    {
        // 1. 验证密码确认
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            throw new ServiceException("两次输入的密码不一致");
        }

        // 2. 检查用户名唯一性
        if (!checkUserNameUnique(registerDTO.getUserName())) {
            throw new ServiceException("用户名已存在");
        }

        // 3. 取消身份证号校验

        // 4. 检查手机号唯一性
        if (!checkPhoneUnique(registerDTO.getPhone())) {
            throw new ServiceException("手机号已存在");
        }

        // 5. 检查邮箱唯一性（如果提供了邮箱）
        if (StringUtils.isNotEmpty(registerDTO.getEmail()) && !checkEmailUnique(registerDTO.getEmail())) {
            throw new ServiceException("邮箱已存在");
        }

        // 6. 创建系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(registerDTO.getUserName());
        sysUser.setNickName(registerDTO.getRealName());
        sysUser.setPassword(SecurityUtils.encryptPassword(registerDTO.getPassword()));
        sysUser.setPhonenumber(registerDTO.getPhone());
        sysUser.setEmail(registerDTO.getEmail());
        sysUser.setStatus("0"); // 正常状态
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setCreateBy("system");

        // 设置飞手角色
        String roleKey = "pilot"; // 飞手注册固定为pilot角色
        try {
            // 先查询所有角色，然后根据roleKey找到对应的角色
            List<SysRole> allRoles = roleService.selectRoleAll();
            SysRole targetRole = null;
            for (SysRole role : allRoles) {
                if (roleKey.equals(role.getRoleKey())) {
                    targetRole = role;
                    break;
                }
            }
            if (targetRole != null) {
                sysUser.setRoleIds(new Long[]{targetRole.getRoleId()});
            } else {
                // 如果找不到对应角色，记录警告但不阻止注册
                System.err.println("警告：未找到角色 " + roleKey + "，用户将注册为普通用户");
            }
        } catch (Exception e) {
            // 如果角色查询失败，记录错误但不阻止注册
            System.err.println("角色查询失败：" + e.getMessage() + "，用户将注册为普通用户");
        }

        int userResult = userService.insertUser(sysUser);
        if (userResult <= 0) {
            throw new ServiceException("用户创建失败");
        }

        // 7. 创建飞手档案
        DroneUserProfile userProfile = new DroneUserProfile();
        userProfile.setUserId(sysUser.getUserId());
        userProfile.setRealName(registerDTO.getRealName());
        // 身份证号取消
        // 设置年龄与飞行年限（可选）
        userProfile.setAge(registerDTO.getAge());
        userProfile.setFlightYears(registerDTO.getFlightYears());
        userProfile.setIdCardFront(registerDTO.getIdCardFront());
        userProfile.setIdCardBack(registerDTO.getIdCardBack());
        userProfile.setPhone(registerDTO.getPhone());
        userProfile.setEmail(registerDTO.getEmail());
        userProfile.setAddress(registerDTO.getAddress());
        userProfile.setEmergencyContact(registerDTO.getEmergencyContact());
        userProfile.setEmergencyPhone(registerDTO.getEmergencyPhone());
        userProfile.setExplorationInfo(registerDTO.getExplorationInfo());
        userProfile.setQualification(registerDTO.getQualification());
        userProfile.setStatus("0"); // 待审核
        userProfile.setCreateTime(DateUtils.getNowDate());
        userProfile.setCreateBy("system");

        int profileResult = userProfileMapper.insertDroneUserProfile(userProfile);
        if (profileResult <= 0) {
            throw new ServiceException("飞手档案创建失败");
        }

        // 8. 创建飞手特定信息
        registerPilotInfo(registerDTO, userProfile.getProfileId());

        return true;
    }

    /**
     * 注册飞手信息（简化版）
     */
    private void registerPilotInfo(DroneRegisterDTO registerDTO, Long pilotId) 
    {
        // 创建证书/资质信息（简化版，只保存证书/资质证明图片）
        if (registerDTO.getCertificates() != null && !registerDTO.getCertificates().isEmpty()) {
            for (String certImage : registerDTO.getCertificates()) {
                DronePilotCertificate certificate = new DronePilotCertificate();
                certificate.setPilotId(pilotId);
                certificate.setCertImage(certImage);
                certificate.setStatus("0"); // 待审核
                certificate.setCreateTime(DateUtils.getNowDate());
                certificate.setCreateBy("system");

                int certResult = certificateMapper.insertDronePilotCertificate(certificate);
                if (certResult <= 0) {
                    throw new ServiceException("证书/资质信息创建失败");
                }
            }
        }

        // 创建技能信息（简化版，只保存技能证明图片）
        if (registerDTO.getSkills() != null && !registerDTO.getSkills().isEmpty()) {
            for (String skillImage : registerDTO.getSkills()) {
                DronePilotSkill skill = new DronePilotSkill();
                skill.setPilotId(pilotId);
                skill.setSkillImage(skillImage);
                skill.setStatus("0"); // 待审核
                skill.setCreateTime(DateUtils.getNowDate());
                skill.setCreateBy("system");

                int skillResult = skillMapper.insertDronePilotSkill(skill);
                if (skillResult <= 0) {
                    throw new ServiceException("技能信息创建失败");
                }
            }
        }
    }

    /**
     * 组织注册
     */
    @Override
    @Transactional
    public boolean registerOrganization(DroneOrganizationRegisterDTO orgRegisterDTO) 
    {
        // 1. 验证密码确认
        if (!orgRegisterDTO.getPassword().equals(orgRegisterDTO.getConfirmPassword())) {
            throw new ServiceException("两次输入的密码不一致");
        }

        // 2. 检查用户名唯一性
        if (!checkUserNameUnique(orgRegisterDTO.getUserName())) {
            throw new ServiceException("用户名已存在");
        }

        // 3. 检查手机号唯一性
        if (!checkPhoneUnique(orgRegisterDTO.getPhone())) {
            throw new ServiceException("手机号已存在");
        }

        // 4. 检查邮箱唯一性（如果提供了邮箱）
        if (StringUtils.isNotEmpty(orgRegisterDTO.getEmail()) && !checkEmailUnique(orgRegisterDTO.getEmail())) {
            throw new ServiceException("邮箱已存在");
        }

        // 5. 检查组织名称唯一性
        if (!checkOrgNameUnique(orgRegisterDTO.getOrgName())) {
            throw new ServiceException("组织名称已存在");
        }

        // 6. 创建系统用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(orgRegisterDTO.getUserName());
        sysUser.setNickName(orgRegisterDTO.getOrgName());
        sysUser.setPassword(SecurityUtils.encryptPassword(orgRegisterDTO.getPassword()));
        sysUser.setPhonenumber(orgRegisterDTO.getPhone());
        sysUser.setEmail(orgRegisterDTO.getEmail());
        sysUser.setStatus("0"); // 正常状态
        sysUser.setCreateTime(DateUtils.getNowDate());
        sysUser.setCreateBy("system");

        // 设置组织角色
        String roleKey = "organization";
        try {
            List<SysRole> allRoles = roleService.selectRoleAll();
            SysRole targetRole = null;
            for (SysRole role : allRoles) {
                if (roleKey.equals(role.getRoleKey())) {
                    targetRole = role;
                    break;
                }
            }
            if (targetRole != null) {
                sysUser.setRoleIds(new Long[]{targetRole.getRoleId()});
            } else {
                System.err.println("警告：未找到角色 " + roleKey + "，用户将注册为普通用户");
            }
        } catch (Exception e) {
            System.err.println("角色查询失败：" + e.getMessage() + "，用户将注册为普通用户");
        }

        int userResult = userService.insertUser(sysUser);
        if (userResult <= 0) {
            throw new ServiceException("用户创建失败");
        }

        // 7. 创建组织信息
        DroneOrganization organization = new DroneOrganization();
        organization.setUserId(sysUser.getUserId());
        organization.setOrgName(orgRegisterDTO.getOrgName());
        organization.setLicenseImage(orgRegisterDTO.getLicenseImage());
        organization.setStatus("0"); // 待审核
        organization.setCreateTime(DateUtils.getNowDate());
        organization.setCreateBy("system");

        int orgResult = organizationMapper.insertDroneOrganization(organization);
        if (orgResult <= 0) {
            throw new ServiceException("组织信息创建失败");
        }

        return true;
    }

    @Override
    public boolean checkUserNameUnique(String userName) 
    {
        SysUser user = new SysUser();
        user.setUserName(userName);
        return userService.checkUserNameUnique(user);
    }



    @Override
    public boolean checkPhoneUnique(String phone) 
    {
        return userProfileMapper.checkPhoneUnique(phone) == 0;
    }

    @Override
    public boolean checkEmailUnique(String email) 
    {
        return userProfileMapper.checkEmailUnique(email) == 0;
    }

    @Override
    public boolean checkOrgNameUnique(String orgName) 
    {
        return organizationMapper.checkOrgNameUnique(orgName) == 0;
    }


}
